using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float turnSpeed = 300f;

    private Vector2 moveInput;
    private Vector2 lookInput;
    private bool jumpInput;
    private bool attackInput;

    private CharacterController controller;
    private Transform cameraTransform;

    private void Awake()
    {
        controller = GetComponent<CharacterController>();
        cameraTransform = Camera.main.transform;
    }

    private void OnEnable()
    {
        PlayerInputActions inputActions = new PlayerInputActions();
        inputActions.Player.Enable();

        inputActions.Player.Move.performed += ctx => moveInput = ctx.ReadValue<Vector2>();
        inputActions.Player.Move.canceled += ctx => moveInput = ctx.ReadValue<Vector2>();

        inputActions.Player.Jump.performed += ctx => jumpInput = true;
        inputActions.Player.Jump.canceled += ctx => jumpInput = false;

        inputActions.Player.Attack.performed += ctx => attackInput = true;
        inputActions.Player.Attack.canceled += ctx => attackInput = false;

        inputActions.Player.Look.performed += ctx => lookInput = ctx.ReadValue<Vector2>();
        inputActions.Player.Look.canceled += ctx => lookInput = ctx.ReadValue<Vector2>();
    }

    private void OnDisable()
    {
        PlayerInputActions inputActions = new PlayerInputActions();
        inputActions.Player.Disable();
    }

    private void Update()
    {
        Move();
        Jump();
        Attack();
    }

    private void Move()
    {
        Vector3 move = new Vector3(moveInput.x, 0, moveInput.y) * moveSpeed * Time.deltaTime;
        controller.Move(move);

        // Rotate the player to face the movement direction
        Quaternion toRotation = Quaternion.LookRotation(move, Vector3.up);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, turnSpeed * Time.deltaTime);
    }

    private void Jump()
    {
        if (jumpInput && controller.isGrounded)
        {
            controller.Move(Vector3.up * 5f);
        }
    }

    private void Attack()
    {
        if (attackInput)
        {
            Debug.Log("Attack!");
        }
    }
}